package com.lyshop.jinding.activitys;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lyshop.jinding.R;
import com.lyshop.jinding.adapters.MyViewPagerAdapter;
import com.lyshop.jinding.base.BaseActivity;
import com.lyshop.jinding.bean.FreshListBean;
import com.lyshop.jinding.bean.ImportDialogBean;
import com.lyshop.jinding.bean.NoviceCouponBean;
import com.lyshop.jinding.eventbus.EventCenter;
import com.lyshop.jinding.eventbus.EventConstants;
import com.lyshop.jinding.net.ActionCallbackListener;
import com.lyshop.jinding.utils.DataUtils;
import com.lyshop.jinding.utils.GlideUtils;
import com.lyshop.jinding.utils.LogUtil;
import com.lyshop.jinding.utils.PermissionInterceptor;
import com.lyshop.jinding.utils.RouteUtil;
import com.lyshop.jinding.utils.TimeCount;
import com.lyshop.jinding.utils.ToastUtil;
import com.lyshop.jinding.utils.ToolbarUtils;
import com.lyshop.jinding.utils.UpdateVersionUtil;
import com.lyshop.jinding.view.FirstPayDialog;
import com.lyshop.jinding.view.GuideTicketDialog;
import com.lyshop.jinding.view.MyDialog;
import com.lyshop.jinding.view.NoScrollViewPager;
import com.zc.mychart.model.GoodsAllBean;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import cn.jpush.android.api.JPushInterface;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    private RadioGroup rg_control_button;
    private RadioButton rb_home;
    private RadioButton rb_market;
    private RadioButton rb_order;
    private RadioButton rb_welfare;
    private RadioButton rb_mine;
    private NoScrollViewPager vp_main;
    public MyViewPagerAdapter mPagerAdapter;
    public static int TAB_HOME = 0;
    public static int TAB_TRADE = 1;
    public static int TAB_ORDER = 2;
    public static int TAB_WELFATE = 3;
    public static int TAB_MY = 4;
    private int mPageIndex;//当前页面index
    private GuideTicketDialog guideTicketDialog;
    private TimeCount mTimeCount;
    private int LOOP_TIME_MILLIS = 5000;//轮询时间
    private FirstPayDialog mFirstPayDialog;
    private MyDialog guideTradeDialog;
    private Dialog mGuideRechargeDialog;
    private UpdateVersionUtil mUpdateVersionUtil;
    private Dialog mToRegisterDialog;
    private Dialog hotActivityDialog;
    private ImageView iv_image;
    private TextView tv_title;
    private TextView tv_content;
    private ImageView bt_close;
    private NestedScrollView nsv_content;
    private TextView tv_link;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!DataUtils.getAgreePermisssion(mContext)){
            Log.d("dangzt", "onCreate: 申请权限");
            XXPermissions.with(this)
                    .permission(Permission.NOTIFICATION_SERVICE)
                    .interceptor(new PermissionInterceptor())
                    .request(new OnPermissionCallback() {

                        @Override
                        public void onGranted(List<String> permissions, boolean all) {
                            Log.d("dangzt", "onCreate: 同意权限");
                            DataUtils.setAgreePermission(mContext, true);
                        }

                        @Override
                        public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                            Log.d("dangzt", "onCreate: 拒绝权限");
                            DataUtils.setAgreePermission(mContext, true);
                        }
                    });
        }
        Log.d("dangzt", "onCreate: 跳过申请权限");
        gotoPush();
        setViewPager();
        checkVersion();
    }

    private void gotoPush() {
        if (!DataUtils.getPushFirstState(MainActivity.this)){
            DataUtils.setPushFirstState(MainActivity.this, true);
            mAppAction.adPost(new ActionCallbackListener<Void>() {
                @Override
                public void onSuccess(Void data) {
                    LogUtil.e("dangzt", "推广上报成功");
                }

                @Override
                public void onFailure(String errorCode, String message) {
                    LogUtil.e("dangzt", "推广上报失败");
                }
            });
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        mPageIndex = getIntent().getIntExtra(RouteUtil.BUNDLE_MAIN_PAGE, TAB_HOME);
        turnToPage(mPageIndex);
    }

    @Override
    protected void onResume() {
        super.onResume();
        clearBadge();
        if (DataUtils.isLogin(mContext)) {
            getHotActivityInfo();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopLoop();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getData(EventCenter center){

    }

    @Override
    protected int setContentView() {
        return R.layout.activity_main;
    }

    @Override
    protected void findViews() {
        rg_control_button = $(R.id.rg_control_button);
        rb_home = $(R.id.rb_home);
        rb_market = $(R.id.rb_market);
        rb_order = $(R.id.rb_order);
        rb_welfare = $(R.id.rb_welfare);
        rb_mine = $(R.id.rb_mine);
        vp_main = $(R.id.vp_main);
    }

    @Override
    protected void setListeners() {
        rg_control_button.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_home:
                mPageIndex = TAB_HOME;
                ToolbarUtils.setStatusTextColor(true, this);
                vp_main.setCurrentItem(0, false);
                break;
            case R.id.rb_market:
                List<GoodsAllBean> allList = myApplication.getAllList();
                if (null != allList && allList.size() > 0) {
                    RouteUtil.toMarketActivity(MainActivity.this, allList.get(0).pro_code);
                } else {
                    ToastUtil.showToast(mContext, "暂未获取商品信息");
                }

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //跳回原来tab
                        turnToPage(mPageIndex);
                    }
                }, 500);
                break;
            case R.id.rb_order:
                if (isUserValidLogin()) {
                    mPageIndex = TAB_ORDER;
                    ToolbarUtils.setStatusTextColor(true, this);
                    vp_main.setCurrentItem(2, false);
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            //跳回原来tab
                            turnToPage(mPageIndex);
                        }
                    }, 500);
                }
                break;
            case R.id.rb_welfare:
                if (isUserValidLogin()) {
                    mPageIndex = TAB_WELFATE;
                    ToolbarUtils.setStatusTextColor(false, this);
                    vp_main.setCurrentItem(3, false);
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            //跳回原来tab
                            turnToPage(mPageIndex);
                        }
                    }, 500);
                }
                break;
            case R.id.rb_mine:
                mPageIndex = TAB_MY;
                ToolbarUtils.setStatusTextColor(false, this);
                vp_main.setCurrentItem(4, false);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onEventComming(EventCenter eventCenter) {
        super.onEventComming(eventCenter);
        int eventCode = eventCenter.getEventCode();
        switch (eventCode) {
            case EventConstants.EVENTCODE_NOVICE_TICKET:
                noviceTicketHandle();
                break;
            case EventConstants.EVENTCODE_UPDATE_PRO_PRICE:
                if (guideTicketDialog != null && guideTicketDialog.isShowing()) {
                    //更新新手下单最新价格
                    guideTicketDialog.refreshProPrice();
                }
                break;
        }
    }

    private void clearBadge() {
        // 如果 badge 数量大于 0，则设置为 0
        JPushInterface.setBadgeNumber(myApplication, 0);
    }

    private void setViewPager() {
        if (mPagerAdapter == null) {
            mPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
            vp_main.setAdapter(mPagerAdapter);
            vp_main.setOffscreenPageLimit(mPagerAdapter.getCount());
            vp_main.setNoScroll(true);
        }
    }

    /**
     * 模拟点击跳转tab
     *
     * @param index
     */
    public void turnToPage(int index) {
        switch (index) {
            case 0:
                rb_home.performClick();
                break;
            case 1:
                rb_market.performClick();
                break;
            case 2:
                rb_order.performClick();
                break;
            case 3:
                rb_welfare.performClick();
                break;
            case 4:
                rb_mine.performClick();
                break;
        }
    }

    /**
     * 版本检测
     */
    private void checkVersion() {
        final String ver = getVersion();
        if (myApplication.getVersionBean() != null){
            String url = myApplication.getVersionBean().getUrl();
            //不在更新中，不在忽略更新时间中
            if (!UpdateVersionUtil.isUpdating
                    && !UpdateVersionUtil.isUpdateCancel()
                    && !TextUtils.isEmpty(url)
                    && isServerVersionNewer(ver, myApplication.getVersionBean().getVersion())) {
                //版本升级弹窗
                mUpdateVersionUtil = new UpdateVersionUtil(mContext, myApplication.getVersionBean().getVersion(),
                        url, myApplication.getVersionBean().getContent(), String.valueOf(myApplication.getVersionBean().getIs_update()));
                mUpdateVersionUtil.checkUpdateInfo();
                mUpdateVersionUtil.setListener(new UpdateVersionUtil.UpgradeDialogListener() {
                    @Override
                    public void onShow() {

                    }

                    @Override
                    public void onDismiss() {
                        initData();
                    }
                });
                if (!mUpdateVersionUtil.isShown()) {
                    initData();
                }
            } else {
                initData();
            }
        }else {
            initData();
        }
    }

    /**
     * 版本比较
     *
     * @param localVer
     * @param serverVer
     * @return
     */
    private boolean isServerVersionNewer(String localVer, String serverVer) {
        try {
            int local = Integer.parseInt(localVer.replaceAll("\\.", ""));
            int server = Integer.parseInt(serverVer.replaceAll("\\.", ""));
            return server > local;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return true;
        }
    }

    /**
     * 获取当前版本
     *
     * @return
     */
    private String getVersion() {
        try {
            PackageManager manager = mContext.getPackageManager();
            PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "Fail";
        }
    }

    /**
     * 不需要更新版本后检查其他弹窗
     */
    private void initData() {
        if (DataUtils.isLogin(mContext)) {
            getHotActivityInfo();
        } else {
            showToRegist();
        }
    }

    /**
     * 重要消息通知
     */
    private void getHotActivityInfo() {
        mAppAction.getImportNoticeDialog(new ActionCallbackListener<ImportDialogBean>() {
            @Override
            public void onSuccess(ImportDialogBean data) {
                if (data != null) {
                    showHotActivityDialog(data);
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {

            }
        });
    }

    /**
     * 重要消息通知弹窗
     */
    private void showHotActivityDialog(ImportDialogBean data) {
        if (null != data && !TextUtils.isEmpty(data.details)) {
            if (null != mUpdateVersionUtil && mUpdateVersionUtil.isShown()) {
                return;
            }
            if (hotActivityDialog == null) {
                hotActivityDialog = new Dialog(mContext, R.style.dialog);
                View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_home_notice, null);
                hotActivityDialog.setContentView(view);
                hotActivityDialog.setCanceledOnTouchOutside(false);
                hotActivityDialog.setCancelable(false);
                Window window = hotActivityDialog.getWindow();
                window.setGravity(Gravity.CENTER);
                iv_image = view.findViewById(R.id.iv_image);
                tv_title = view.findViewById(R.id.tv_title);
                tv_content = view.findViewById(R.id.tv_content);
                bt_close = view.findViewById(R.id.bt_close);
                nsv_content = view.findViewById(R.id.nsv_content);
                tv_link = view.findViewById(R.id.tv_link);
            }
            if (data.noticeType == 1) {
                tv_title.setVisibility(View.GONE);
                nsv_content.setVisibility(View.GONE);
                tv_link.setVisibility(View.GONE);
                iv_image.setVisibility(View.VISIBLE);
                bt_close.setVisibility(View.VISIBLE);

                GlideUtils.showImageFitxyOptions(mContext, data.content, iv_image);
            } else {
                iv_image.setVisibility(View.GONE);
                bt_close.setVisibility(View.GONE);
                tv_title.setVisibility(View.VISIBLE);
                nsv_content.setVisibility(View.VISIBLE);
                tv_link.setVisibility(View.VISIBLE);

                tv_title.setText(data.title);
                tv_content.setText(data.content);
            }
            tv_link.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    RouteUtil.routePageByUrl(MainActivity.this, data.details);
                    hotActivityDialog.dismiss();
                }
            });
            bt_close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    hotActivityDialog.dismiss();
                }
            });
            iv_image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    RouteUtil.routePageByUrl(MainActivity.this, data.details);
                    hotActivityDialog.dismiss();
                }
            });
            mAppAction.readNotice(data.id, new ActionCallbackListener<Void>() {
                @Override
                public void onSuccess(Void data) {

                }

                @Override
                public void onFailure(String errorCode, String message) {

                }
            });

            if (!hotActivityDialog.isShowing()) {
                hotActivityDialog.show();
            }
        }
    }

    /**
     * 没有登录注册，显示注册弹窗
     */
    private void showToRegist() {
        if (mToRegisterDialog == null) {
            mToRegisterDialog = new Dialog(mContext, R.style.dialog);
            View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_guide_reg, null);
            ImageView bt_close_register = view.findViewById(R.id.iv_close_register);
            ImageView bt_guide_register = view.findViewById(R.id.iv_guide_register);
            bt_close_register.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mToRegisterDialog.cancel();
                }
            });
            bt_guide_register.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onLogoutStatus();
                    mToRegisterDialog.cancel();
                }
            });
            mToRegisterDialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            mToRegisterDialog.setCanceledOnTouchOutside(false);
            mToRegisterDialog.setCancelable(false);
            Window window = mToRegisterDialog.getWindow();
            window.setGravity(Gravity.CENTER);
        }
        if (!mToRegisterDialog.isShowing()) {
            mToRegisterDialog.show();
        }
    }

    /**
     * 有新手券弹出新手单弹窗
     */
    private void noviceTicketHandle() {
        NoviceCouponBean noviceCoupon = DataUtils.getUserInfo(mContext).noviceCoupon;
        GoodsAllBean goodsAllBean = myApplication.getAllGoodMap().get(noviceCoupon.contractCode);
        if (goodsAllBean.during_type == 1) {
            //开市弹出下单弹窗
            initGuideTicketDialog();
            if (!guideTicketDialog.isShowing()) {
                guideTicketDialog.setData(DataUtils.getUserInfo(mContext).noviceCoupon);
            }
        } else {
            showGuideTradeDialog();
        }
    }

    /**
     * 新手开市弹窗
     */
    private void initGuideTicketDialog() {
        if (guideTicketDialog == null) {
            guideTicketDialog = new GuideTicketDialog(mContext, new GuideTicketDialog.GuideTicketListener() {
                @Override
                public void onSuccess() {
                    //下单成功
                    startLoop();
                    turnToPage(MainActivity.TAB_ORDER);
                }

                @Override
                public void onFailed() {
                    //下单失败
                    if (null != guideTicketDialog && guideTicketDialog.isShowing()) {
                        guideTicketDialog.dismiss();
                    }
                }

                @Override
                public void onCancel() {
                }

                @Override
                public void onLoading() {
                    loading();
                }

                @Override
                public void onLoadingCancel() {
                    cancelLoading();
                }
            });
        }
    }

    /**
     * 新手闭市弹窗
     */
    private void showGuideTradeDialog() {
        if (null == guideTradeDialog) {
            guideTradeDialog = new MyDialog(this);
            View view = LayoutInflater.from(this).inflate(R.layout.dialog_guide_start, null);
            View rl_guide_view = view.findViewById(R.id.rl_guide_view);
            rl_guide_view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    RouteUtil.toTicketActivity((BaseActivity) mContext);
                    if (null != guideTradeDialog && guideTradeDialog.isShowing()) {
                        guideTradeDialog.dismiss();
                    }
                }
            });
            guideTradeDialog.setContentView(view);
        }
        if (!guideTradeDialog.isShowing()) {
            guideTradeDialog.show();
        }
    }

    /**
     * 开启轮询，查询新手单结果
     */
    public void startLoop() {
        if (null == mTimeCount) {
            mTimeCount = new TimeCount(12 * 60 * 60 * 1000, LOOP_TIME_MILLIS) {
                @Override
                public void onTick(long millisUntilFinished) {
                    getPushList();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                }
            };
        } else {
            mTimeCount.cancel();
        }
        mTimeCount.start();
    }

    /**
     * 停止新手单结果查询
     */
    public void stopLoop() {
        if (null != mTimeCount) {
            mTimeCount.cancel();
        }
    }

    /**
     * 获取新手单结果
     */
    public void getPushList() {
        mAppAction.loopPushList(new ActionCallbackListener<FreshListBean>() {
            @Override
            public void onSuccess(FreshListBean data) {
                if (null != data && data.send_type > 0) {
                    stopLoop();
                    showFreshResultDialog(data);
                    upload(data);
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
            }
        });
    }

    /**
     * 新手购买结果弹窗
     *
     * @param bean
     */
    private void showFreshResultDialog(FreshListBean bean) {
        if (null == mFirstPayDialog) {
            mFirstPayDialog = new FirstPayDialog(mContext, new FirstPayDialog.DialogListener() {
                @Override
                public void onConfirm(FreshListBean bean) {
                    if (null != bean) {
                        if (bean.send_type == 1) {
                            RouteUtil.toRechargeActivity(MainActivity.this);
                        }
                        myApplication.updateUserDetail();
                    }
                }
            });
        }
        mFirstPayDialog.setFreshListBean(bean);
        if (!mFirstPayDialog.isShowing()) {
            mFirstPayDialog.show();
        }
    }

    /**
     * 新手单结果上报
     *
     * @param
     */
    public void upload(FreshListBean freshListBean) {
        if (freshListBean == null) return;
        mAppAction.uploadPushId(freshListBean.id, new ActionCallbackListener<Void>() {
            @Override
            public void onSuccess(Void data) {
                if (freshListBean.send_type == 2) {
                    myApplication.updateUserDetail();
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {

            }
        });

    }

    /**
     * 新手单结束后充值弹窗
     */
    public void showGuideRechargeDialog() {
        if (mGuideRechargeDialog == null) {
            mGuideRechargeDialog = new Dialog(mContext, R.style.dialog);
            View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_guide_recharge, null);
            ImageView iv_image = view.findViewById(R.id.iv_image);
            TextView tv_close = view.findViewById(R.id.tv_close);
            iv_image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != mGuideRechargeDialog && mGuideRechargeDialog.isShowing()) {
                        mGuideRechargeDialog.dismiss();
                    }
                    RouteUtil.toRechargeActivity((BaseActivity) mContext);
                }
            });
            tv_close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != mGuideRechargeDialog && mGuideRechargeDialog.isShowing()) {
                        mGuideRechargeDialog.dismiss();
                    }
                }
            });
            mGuideRechargeDialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            mGuideRechargeDialog.setCanceledOnTouchOutside(false);
            mGuideRechargeDialog.setCancelable(false);
            Window window = mGuideRechargeDialog.getWindow();
            window.setGravity(Gravity.CENTER);
        }
        if (!mGuideRechargeDialog.isShowing()) {
            mGuideRechargeDialog.show();
        }
        DataUtils.setGuideBuy(mContext, false);
    }
}